<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/8
 * Time: 15:44
 */

namespace App\Rep;


use App\Imports\MultipleImport;
use App\Models\ModelNumber;
use App\Models\ModelNumberSpecification;
use App\Models\Product;
use App\Models\ProductCenter;
use App\Models\ProductColor;
use App\Models\ProductJobType;
use App\Models\ProductModelNumber;
use App\Models\ProductPrice;
use App\Models\Specification;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ProductRep
{

    /**
     * 获取产品列表
     * @param $params
     */
    public function getProductListRep($params){

        $list = Product::Search($params)->with(['product_models'=>function($q){
            $q->select('modelid','modelname');
        }])->orderBy('id','desc')->paginate($params['per_page']??1000);

        return $list;
    }

    public function getProductDropDownListRep($params){
        $list =  Product::Search($params)->with('model_number')
            ->select('id','product_name','modelid')->get();
        //dd($list);
//        foreach($list as $k=>$v){
//            foreach($v->price as $kk=>$vv){
//                if($v->modelid == 1){
//                    //沙发
////                    $price = ProductPrice::where('model_number_id',$vv->id)
////                        ->where('product_id',$v->id)->value('unit_price');
////                    $list[$k]->price[$kk]->unit_price = $price??0;
//                    $list[$k]->price[$kk]->unit_price = 0;
//                }else{
//                    foreach($vv->specification as $kkk=>$vvv){
////                        $price = ProductPrice::where('model_number_id',$vv->id)
////                            ->where('product_id',$v->id)
////                            ->where('specification_id',$vvv->id)
////                            ->value('unit_price');
////                        $list[$k]->price[$kk]->specification[$kkk]->unit_price = $price;
//                        $list[$k]->price[$kk]->specification[$kkk]->unit_price = 0;
//                    }
//                }
//            }
//        }
        return $list;
    }

    /**
     * 添加产品
     * @param $params
     */
//    public function createProductRep($params){
//        DB::beginTransaction();
//        try {
//            if(!empty($params['id'])){
//                //编辑
//                $product = Product::where('id',$params['id'])->first();
//                $product->product_name = $params['product_name'];
//                $product->sort = $params['sort']??'';
//
//            }else{
//
//                $product = new Product();
//                $product->product_name = $params['product_name'];
//                $product->sort = $params['sort']??'';
//
//            }
//            $product->save();
//            //颜色
//            foreach($params['color_ids'] as $k=>$v){
//                ProductColor::updateOrCreate(
//                    ['product_id'=>$product->id,'color_id'=>$v],
//                    ['product_id'=>$product->id,'color_id'=>$v]
//                );
//            }
//
//            //工序
//            ProductJobType::where(['product_id'=>$product->id])->delete();
//            foreach($params['job_type'] as $k=>$v){
//                $insertArr[] = ['product_id'=>$product->id,'job_type_id'=>$v['job_type_id'],'sort'=>$v['sort']];
//            }
//            ProductJobType::insert($insertArr);
//
//            DB::commit();
//            return ['code'=>0,'data'=>[],'msg'=>''];
//        }catch(\Exception $e){
//            DB::rollBack();
//            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
//        }
//
//    }



    /**
     * 添加产品
     */
    public function createProductRep($params){
        DB::beginTransaction();
        try {
            if(!empty($params['id'])){
                //编辑
                $product = Product::where('id',$params['id'])->first();
                $product->product_name = $params['product_name'];
                if(isset($params['modelid']) && !empty($params['modelid'])){
                    $product->modelid = $params['modelid'];
                }
                $product->able_level = $params['able_level']??1;
                $product->save();
            }else{

                $product = new Product();
                $product->product_name = $params['product_name'];
                $product->able_level = $params['able_level']??1;
                if (strpos($params['product_name'], ',') !== false) {
                    //批量添加
                    $product_name_list = explode(',',$params['product_name']);
                    foreach($product_name_list as $k=>$v){
                        Product::updateOrCreate(['product_name'=>$v,'modelid'=>$params['modelid']],['product_name'=>$v,'modelid'=>$params['modelid'],'is_del'=>2,'able_level'=>$params['able_level']??1]);
                    }
                } else {
                    //单个添加
                    Product::updateOrCreate(['product_name'=>$params['product_name']],['product_name'=>$params['product_name'],'modelid'=>$params['modelid'],'is_del'=>2,'able_level'=>$params['able_level']??1]);
                }

            }
            //颜色
//            foreach($params['color_ids'] as $k=>$v){
//                ProductColor::updateOrCreate(
//                    ['product_id'=>$product->id,'color_id'=>$v],
//                    ['product_id'=>$product->id,'color_id'=>$v]
//                );
//            }

            DB::commit();
            return ['code'=>0,'data'=>$product,'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }

    }


    /**
     * 删除
     * @param $params
     * @return array
     */
    public function delProductRep($params){
        DB::beginTransaction();
        try {
            $product = Product::where('id',$params['id'])->first();
            $product->is_del = 1;
            $product->save();
            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }

    }

    /**
     * 添加产品颜色
     * @param $params
     */
    public function addProductColorRep($params){
        $color_ids = $params['color_ids'];
        foreach($color_ids as $k=>$v){
            $where = ['product_id'=>$params['product_id'],'color_id'=>$v];
            ProductColor::updateOrCreate($where,$where);
        }
        return true;
    }

    //获取产品颜色列表
    public function getProductColorListRep($params){
        $product = Product::where('id',$params['product_id'])->first();
        $list = $product->color()->get();
        return $list;
    }

    /**
     * 删除产品颜色
     * @param $params
     */
    public function delProductColorRep($params){
        ProductColor::where('color_id',$params['color_id'])->where('product_id',$params['product_id'])->delete();
    }

    //添加产品工种
    public function addProductJobTypeRep($params){
        Product::where('id',$params['product_id'])->update(['sort_info'=>'']);
        foreach($params['job_type_ids'] as $k=>$v){
            $where = ['job_type_id'=>$v,'product_id'=>$params['product_id']];
            ProductJobType::updateOrCreate($where,$where);
        }
        return true;
    }


    //移除产品工种关联
    public function delProductJobTypeRep($params){
        Product::where('id',$params['product_id'])->update(['sort_info'=>'']);
        ProductJobType::where('product_id',$params['product_id'])->where('job_type_id',$params['job_type_id'])->delete();
        ProductJobType::where('product_id',$params['product_id'])->update(['pid'=>'']);
        return true;
    }

    public function getProductJobTypeSortRep($params){
        return Product::where('id',$params['product_id'])->value('sort_info');
    }


    //设置产品工种排序
    public function setProductJobTypeSortRep($params){
        DB::beginTransaction();
        try{
            Product::updateOrCreate(
                ['id'=>$params['product_id']],
                    ['sort_info'=>$params['sort_info']]
                );
            $sortInfo = $this->getSortInfo($params['sort_info']);
            //p($sortInfo);
            foreach($sortInfo as $k=>$v){
                ProductJobType::updateOrCreate(
                    ['product_id'=>$params['product_id'],'job_type_id'=>$v['id']],
                    ['pid'=>implode(',',$v['pid'])]);
            }
            $list = ProductJobType::where('product_id',$params['product_id'])->get();
            foreach($list as $k=>$v){
                $sort = $this->setProductJobTypeListSortRep($v->product_id,$v->job_type_id);
                $v->sort = $sort;
                $v->save();
            }

            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }

    /**
     * 解析sort_info数据
     * @param $sort_info
     * @return array
     */
    public function getSortInfo($sort_info){
        $sort_info_arr = json_decode($sort_info,true);
        //p($sort_info_arr);
        $nodeList = $sort_info_arr['nodeList'];
        $linkList = $sort_info_arr['linkList'];
        $newarr = [];
        $node_id_list = array_column($nodeList, 'id');
        foreach($linkList as $k=>$v){
            $node_id_pid_key = array_search($v['startId'],$node_id_list);
            $node_id_key = array_search($v['endId'],$node_id_list);
            $newarr[$k]['pid'] = $nodeList[$node_id_pid_key]['meta']['id'];
            $newarr[$k]['id'] = $nodeList[$node_id_key]['meta']['id'];
        }
        $data = [];
        foreach($nodeList as $k=>$v){
            $data[$k]['id'] = $v['meta']['id'];
            foreach($newarr as $kk=>$vv){
                if($vv['id'] == $v['meta']['id']){
                    $data[$k]['pid'][] = $vv['pid'];
                }
            }
        }
        foreach ($data as $k=>$v){
            if(!isset($v['pid'])){
                $data[$k]['pid'] = [0];
            }
        }

        //p($nodeList);
        return $data;
    }



    /**
     * 通过product_id获取产品的工种列表
     * @param $product_id
     * @return mixed
     */
    public function getProductJobTypeListByProductId($product_id){
        $product = Product::where('id',$product_id)->with('job_type')->first();
        $product_arr = $product->toArray();
        $job_type_list = $product_arr['job_type'];
        return $job_type_list;
    }

    /**
     * 对产品工种进行排序
     */
    public function setProductJobTypeListSortRep($product_id,$job_type_id,$int=1){
        $pidstr = ProductJobType::where('product_id',$product_id)->where('job_type_id',$job_type_id)->value('pid');
        if($pidstr == 0){
            return $int;
        }else{
            $pid_arr = explode(',',$pidstr);
            if(count($pid_arr)>1){
                for($i=0;$i<count($pid_arr);$i++){
                    $int = $int + 1;
                    return $this->setProductJobTypeListSortRep($product_id,$pid_arr[$i],$int);
                }
            }else{
                $int = $int +1;
                return $this->setProductJobTypeListSortRep($product_id,$pid_arr[0],$int);
            }

        }
    }

    //获取工种的生产顺序
    public function getProductJobTypeListSortRep($product_id,$job_type_id){
        $sort = ProductJobType::where('product_id',$product_id)
            ->where('job_type_id',$job_type_id)
            ->value('sort');
        return $sort;
    }



    /**
     * 通过product_id获取产品的型号列表
     * @param $product_id
     */
    public function getModelNumberByProductRep($product_id){
        $ids = ProductModelNumber::where('product_id',$product_id)->pluck('model_number_id')->toArray();
        $model_number = ModelNumber::whereIn('id',$ids)->paginate(10);
        return $model_number;
    }

    /**
     * 获取产品关联的半成品列表
     * @param $product_id
     * @return mixed
     */
    public function getSemiListByProductIdRep($product_id){
        $modelid = Product::where('id',$product_id)->value('modelid');
        $models = new ModelRep();
        return $models->getSemiListByFinishRep($modelid);
    }

    /**
     * 获取工种价格
     * @return void
     */
    public function getPriceByJobTypeId($product_id,$model_number_id,$job_type_id,$specification_id){
        $model = ProductCenter::query();
        $model->where('product_id',$product_id);
        $model->where('model_number_id',$model_number_id);
        if($specification_id != 0 && $specification_id != null){
            $model->where('specification_id',$specification_id);
        }
        $model->where('job_type_id',$job_type_id);
        $price = $model->value('price');
        return $price??0;
    }

    /**
     * excel导入
     * @param $file_url
     * @return void.
     */
    public function productImportRep($file_url){
        $file = public_path($file_url);
        $import = new MultipleImport(1);
        Excel::import($import, $file);
        $results = $import->sheet[0]->data->toArray();
        unset($results[0]);
        unset($results[1]);
        DB::beginTransaction();
        try {
            $err_data = [];
            foreach($results as $k=>$v){
                $product_name = trim($v[0]);
                if(empty($product_name)){
                    continue;
                }
                $model_number = trim($v[1]);
                $specification = trim($v[2]);

                $product_obj = Product::updateOrCreate(['product_name'=>$product_name],['product_name'=>$product_name,'is_del'=>2]);
                $model_number_obj = ModelNumber::updateOrCreate(['model_number'=>$model_number],['model_number'=>$model_number]);
                ProductModelNumber::updateOrCreate(
                    ['model_number_id'=>$model_number_obj->id,'product_id'=>$product_obj->id],
                    ['model_number_id'=>$model_number_obj->id,'product_id'=>$product_obj->id]
                );

                $specification_obj = Specification::updateOrCreate(['specification'=>$specification],['specification'=>$specification]);

                ModelNumberSpecification::updateOrCreate(
                    ['model_number_id'=>$model_number_obj->id,'specification_id'=>$specification_obj->id],
                    [
                        'model_number_id'=>$model_number_obj->id,
                        'specification_id'=>$specification_obj->id,
                        'product_id'=>$product_obj->id
                    ]
                );
            }
            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>'导入成功，共'.count($results).'条数据'];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }


}
